package com.wfcm.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wfcm.entity.*;
import com.wfcm.service.*;
import com.wfcm.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.exception.WFCMException;
import com.wfcm.wxPay.MD5Util;
import com.wfcm.wxPay.ResponseHandler;
import com.wfcm.wxPay.WXOrderQuery;
import com.wfcm.wxPay.WXPayUtil;

@Controller
@RequestMapping("/ggOrder")
@ResponseBody
public class GgOrderController {

	private Logger log = LoggerFactory.getLogger(AdInfoController.class);
	@Autowired
	private WfGoodsOrderService goodsOrderService;
	@Autowired
	private WfMemberService memberService;
	@Autowired
	private WfGoodsOrderRelationService goodsOrderRelationService ;	
	@Autowired
	private WfCoinLogService coinLogService ;
	@Autowired
	private WfMemberCouponsService memberCouponsService ;
	@Autowired
	private WfCourseChapterService courseChapterService;
	@Autowired
	private WfCourseInfoService courseInfoService;
	@Autowired
	private WfVipCardService vipCardService;
	@Autowired
	private WfActivityService activityService;
	@Autowired
	private WfMemberInvitationService invitationService;
	@Autowired
	private WfBillService billService;
	@Autowired
	private WfShoppingCartService shoppingCartService;
	@Autowired
	private WfMemberGoldLogService memberGoldLogService ;
	@Autowired
	private WfMemberNewGoldLogService memberNewGoldLogService ;
	@Autowired
	private WfMemberGiveCoinLogService memberGiveCoinLogService ;
	@Autowired
	private WfRechargeService rechargeService ;
	@Autowired
	private WfMemberRechargeOrderService memberRechargeOrderService;
	@Autowired
	private WfCourseGiftService courseGiftService;
	@Autowired
	private WfCollageOrderService  collageOrderService;
	@Autowired
	private DistributionService distributionService;
	
	/**
     * 微信回调
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wechatreceive")
    @IgnoreSign
    @IgnoreToken
    @ResponseBody
    public void wechatreceive(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResponseHandler resHandler = new ResponseHandler(request, response);
        try {
            log.info("微信支付==进入==");
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            resHandler.setKey(ConstantUtil.GG_APP_KEY);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            response.setHeader("ContentType", "text/xml");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            outSteam.close();
            inStream.close();

            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            log.info("微信支付==result==" + result);
            Map<Object, Object> map = XMLUtil.doXMLParse(result);
            log.info("微信支付==map==" + map);

            String result_code = "";
            String out_trade_no = "";
            String trade_no = "";
            String total_fee ="";
            String time_end ="";
            for (Object keyValue : map.keySet()) {
                result_code = map.get("result_code").toString();//业务结果
                out_trade_no = map.get("out_trade_no").toString();//商户订单号
                trade_no = map.get("transaction_id").toString();//微信支付订单号
                total_fee = map.get("total_fee").toString();//总金额
                time_end = map.get("time_end").toString();//支付完成时间
            }
            
            WfGoodsOrderEntity  goodsOrder = goodsOrderService.queryByOrderCode(out_trade_no);
            
            // 判断
            if(!WXPayUtil.isSignatureValid(result,ConstantUtil.GG_APP_KEY)){
                log.info("微信验签失败");
                resHandler.sendToCFT("FAIL");
            }
            if ("SUCCESS".equals(result_code) ) {
            	//支付成功后，课程销量增加，优惠券减少，铜钱余额减少，订单状态为已完成，铜钱奖励邀请人
            	Map<String,Object> map1 =new  HashMap<String,Object>();
            	map1.put("orderCode", out_trade_no);
            	WfMemberRechargeOrderEntity memberRechargeOrder = memberRechargeOrderService.queryByOrderNum(map1);//根据订单号获取充值数据
            	if(null != memberRechargeOrder) {//不为空，说明为进行充值操作
            		System.out.println("*********************************充值订单："+memberRechargeOrder.toString()+"*************************");
            		memberRechargeOrder.setOrderStatus(3);//订单类型（1生成订单2支付中3支付成功）
            		memberRechargeOrder.setTransactionId(trade_no);//微信订单号
            		memberRechargeOrderService.update(memberRechargeOrder);
           
            	}else {
	            	List<WfGoodsOrderRelationEntity> goodsOrderRelationList = goodsOrderRelationService.queryList(map1);
	            	if(goodsOrderRelationList.size()>0) {
			        	for(int i=0; i<goodsOrderRelationList.size(); i++) {
			        		WfGoodsOrderRelationEntity goodsOrderRelation = goodsOrderRelationList.get(i);
			        		goodsOrderRelation.setOrderstatus(4);//关联订单状态为成功
			        		goodsOrderRelationService.update(goodsOrderRelation);//保存
			        		if(1 == goodsOrderRelation.getGoodssort()) {
			    				WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
			    				if(null == courseInfo) {
			    					System.out.println("关联课程为空");
			    				}
			    				int salenum = courseInfo.getCoursesalenumber() + 1;
			    				courseInfo.setCoursesalenumber(salenum);
			    				courseInfoService.update(courseInfo);
			    			}else if(2 == goodsOrderRelation.getGoodssort()){
			    				WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
			    				if(null == courseChapter) {
			    					System.out.println("关联章节为空");
			    				}
			    				int salenum = courseChapter.getChaptersalenumber() + 1;
			    				courseChapter.setChaptersalenumber(salenum);
			    				courseChapterService.update(courseChapter);
			    			}else if(3 == goodsOrderRelation.getGoodssort()){
			    				WfVipCardEntity vipCard = vipCardService.queryObject(goodsOrderRelation.getGoodsid());
			    				if(null == vipCard) {
			    					System.out.println("关联课程包为空");
			    				}
			    				int salenum = vipCard.getCardsalenumber() + 1;
			    				vipCard.setCardsalenumber(salenum);
			    				vipCardService.update(vipCard);
			    			}
			        	}

						//订单状态
						goodsOrder.setOrderstatus(4);//改为已完成
						goodsOrder.setTransactionId(trade_no);//微信订单号
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
						goodsOrder.setOrderpaytime(sdf.parse(time_end));
						goodsOrderService.update(goodsOrder);

						/**
						 * 分销
						 */
						Map<String, Object> map2 = new HashMap<>(), map3 = new HashMap<>(), map4 = new HashMap<>();
						map2.put("uid", goodsOrder.getUserid());
						map2.put("orderStatus", 4);
						map3.put("invitedId", goodsOrder.getUserid());
						map4.put("orderCode", goodsOrder.getOrdercode());
						Distribution distribution = distributionService.configuration();
						List<WfGoodsOrderEntity> goodsOrderList = goodsOrderService.queryList(map2);
						List<WfMemberInvitationEntity> invitationList = invitationService.queryList(map3);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(new Date());
						calendar.add(Calendar.DATE, -distribution.getNum());
						if (invitationList.size() > 0) {
							WfMemberInvitationEntity invitation = invitationList.get(0);
							if (calendar.getTime().getTime() <= invitationList.get(0).getCreatetime().getTime()) {
								goodsOrderRelationService.queryList(map4).forEach(item -> {
									if (distributionService.searchGoods(item.getGoodsid(), item.getGoodssort())) {
										BigDecimal decimal = new BigDecimal(0);
										Integer commissionRate = distributionService.searchGoodsInfo
												(item.getGoodsid(), item.getGoodssort()).getCommissionRate();
										decimal = decimal.add(item.getOldcoppercash() != null ? item.getOldcoppercash() : new BigDecimal(0))
												.add(item.getNewcoppercash() != null ? item.getNewcoppercash() : new BigDecimal(0))
												.add(item.getGold() != null ? item.getGold() : new BigDecimal(0))
												.add(item.getRealpay() != null ? item.getRealpay() : new BigDecimal(0))
												.add(item.getNewGold() != null ? item.getNewGold() : new BigDecimal(0))
												.multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));
										WfMemberGiveCoinLogEntity reward = new WfMemberGiveCoinLogEntity();
										reward.setUserid(invitation.getInviterid());
										reward.setTouserid(goodsOrder.getUserid());
										reward.setType(1); // 1 赚 2 花
										reward.setStatus(2); // 1 审核中 2 成功
										reward.setSource(2);
										reward.setCoinvalue(decimal);
										reward.setCreatetime(new Date());
										reward.setOrdercode(goodsOrder.getOrdercode());
										reward.setRemarkinfo("邀请用户买课赠送铜钱");
										memberGiveCoinLogService.save(reward);
										Long time = System.currentTimeMillis() / 1000;
										distributionService.addRecord(new Distribution(invitation.getInviterid(), goodsOrder.getUserid(), goodsOrder.getOrdercode(), decimal.doubleValue(),
												1, time.intValue(), time.intValue(), item.getGoodsid(), item.getGoodssort(), commissionRate));
									}
								});
							} else if (goodsOrderList.size() == 1) {
								// 邀请关系过期，首单返还。
								goodsOrderRelationService.queryList(map4).forEach(item -> {
									BigDecimal decimal = new BigDecimal(0);
									Integer commissionRate = distribution.getCommissionRate();
									decimal = decimal.add(item.getOldcoppercash() != null ? item.getOldcoppercash() : new BigDecimal(0))
											.add(item.getNewcoppercash() != null ? item.getNewcoppercash() : new BigDecimal(0))
											.add(item.getGold() != null ? item.getGold() : new BigDecimal(0))
											.add(item.getRealpay() != null ? item.getRealpay() : new BigDecimal(0))
											.add(item.getNewGold() != null ? item.getNewGold() : new BigDecimal(0))
											.multiply(new BigDecimal(commissionRate)).divide(new BigDecimal(100));
									WfMemberGiveCoinLogEntity reward = new WfMemberGiveCoinLogEntity();
									reward.setUserid(invitation.getInviterid());
									reward.setTouserid(goodsOrder.getUserid());
									reward.setType(1); // 1 赚 2 花
									reward.setStatus(2); // 1 审核中 2 成功
									reward.setSource(2);
									reward.setCoinvalue(decimal);
									reward.setCreatetime(new Date());
									reward.setOrdercode(goodsOrder.getOrdercode());
									reward.setRemarkinfo("邀请用户买课首单赠送铜钱");
									memberGiveCoinLogService.save(reward);
									Long time = System.currentTimeMillis() / 1000;
									distributionService.addRecord(new Distribution(invitation.getInviterid(), goodsOrder.getUserid(), goodsOrder.getOrdercode(), decimal.doubleValue(),
											1, time.intValue(), time.intValue(), item.getGoodsid(), item.getGoodssort(), commissionRate));
								});
							}
						}

		        		//原铜钱余额
		        		WfCoinLogEntity coinLog = coinLogService.queryByOrderCode(out_trade_no);
		        		if(coinLog != null) {
		        			coinLog.setStatus(2);//成功
		        			coinLogService.update(coinLog);
		        		}
	            	}

					//新金币
					WfMemberNewGoldLogEntity memberNewGoldLog = memberNewGoldLogService.queryByOrderCode(out_trade_no);
					if(memberNewGoldLog != null) {
						memberNewGoldLog.setStatus(2);//成功
						memberNewGoldLogService.update(memberNewGoldLog);
					}
	            	
	            	//金币
	        		WfMemberGoldLogEntity memberGoldLog = memberGoldLogService.queryByOrderCode(out_trade_no);
	        		if(memberGoldLog != null) {
	        			memberGoldLog.setStatus(2);//成功
	        			memberGoldLogService.update(memberGoldLog);
	        		}
	            	
	    			//新铜钱
	        		map1.put("type", 2);
	        		List<WfMemberGiveCoinLogEntity> memberGiveCoinLogList = memberGiveCoinLogService.queryByOrderCode(map1);
	        		if(memberGiveCoinLogList.size()>0) {
	        			memberGiveCoinLogList.get(0).setStatus(2);//成功
	        			memberGiveCoinLogService.update(memberGiveCoinLogList.get(0));
	        		}
            	}
            	
                log.info("微信支付，交易成功");
                resHandler.sendToCFT("SUCCESS");
            }else {
                log.info("微信支付失败");
                resHandler.sendToCFT("FAIL");
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                resHandler.sendToCFT("FAIL");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 查询微信账单
     * @throws Exception
     */
    @RequestMapping(value = "doQuery")
    @IgnoreSign
    @IgnoreToken
    @ResponseBody
    public R doQuery(HttpServletRequest req) throws Exception {
    	String orderNum = req.getParameter("orderNum");//购物订单查询
    	//String transactionId = goodsOrder.getTransactionId();
    	 // 商户相关资料
    	
    	Map<String,String> map = new HashMap<String,String>();
    	while(!("SUCCESS".equals(map.get("trade_state")))) {
    		orderNum = req.getParameter("orderNum");//购物订单查询
    		WfGoodsOrderEntity goodsOrder = new WfGoodsOrderEntity();
    		goodsOrder = goodsOrderService.queryByOrderCode(orderNum);
    		
	        String appid = ConstantUtil.GG_APP_ID;
	        // String appsecret = ConstantUtil.APP_SECRET;
	        String partner = ConstantUtil.GG_PARTNER;
	        String partnerkey = ConstantUtil.GG_PARTNER_KEY;
	    	
	    	WXOrderQuery query = new WXOrderQuery();
	    	query.setAppid(appid);//应用APPID
	    	query.setMch_id(partner);//商户号
	    	Random random = new Random();
			String randomStr = MD5Util.MD5Encode(String.valueOf(random.nextInt(1000000)), "utf-8").toUpperCase();
			System.out.println("randomStr="+randomStr);
			query.setNonce_str(MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase());//随机字符串
	    	query.setOut_trade_no(orderNum);//商户订单号
	    	query.setPartnerKey(partnerkey);//API秘钥
	    	//query.setTransaction_id(transactionId);//微信订单号(或商户订单号 二选一)
	    	query.setSign(createSign(query, partnerkey));//签名
	    	
	    	map = query.reqOrderquery();
    	
	    	if("SUCCESS".equals(map.get("trade_state"))) {
	    		
	    		WfBillEntity b = billService.queryByOrderNum(orderNum);
	    		if(null == b) {
		    		WfBillEntity bill = new WfBillEntity();
		        	bill.setTradetime(map.get("time_end"));//支付完成时间
		        	bill.setGhid(map.get("appid"));//app/公众号id
		        	bill.setMchid(map.get("mch_id"));//商户号
		        	bill.setSubmch("0");//子商户号
		        	bill.setDeviceid(map.get("device_info"));//设备号
		        	bill.setWxorder(map.get("transaction_id"));//微信支付订单号
		        	bill.setBzorder(map.get("out_trade_no"));//商户订单号
		        	bill.setOpenid(map.get("openid"));//用户标识
		        	bill.setTradetype(map.get("trade_type"));//交易类型
		        	bill.setTradestatus(map.get("trade_state"));//交易状态   SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVOKED—已撤销（刷卡支付） USERPAYING--用户支付中 PAYERROR--支付失败(其他原因，如银行返回失败)
		        	bill.setBank(map.get("bank_type"));//付款银行
		        	bill.setCurrency(map.get("fee_type"));//货币种类
		        	bill.setTotalmoney(map.get("cash_fee"));//现金支付金额
		        	bill.setRedpacketmoney(map.get("coupon_fee"));//代金券金额
		        	bill.setOpenid(map.get("openid"));//代金券金额
		        	bill.setWxrefund("0");//微信退款单号
		        	bill.setBzrefund("0");//商户退款单号
		        	bill.setRefundmoney("0.00");//退款金额openid
		          //bill.setRefundtype((String) map.get("time_end"));//退款类型
		          //bill.setRefundstatus((String) map.get("time_end"));//退款状态
		        	String productname = "";
		        	if("".equals(orderNum)) {//若购物订单号为空，则说明在操作充值
		        		bill.setProductname("充值");
		        	}else {
		        		Map<String,Object> map1 =new  HashMap<String,Object>();
			        	map1.put("orderCode", goodsOrder.getOrdercode());
			        	List<WfGoodsOrderRelationEntity> goodsOrderRelationList = goodsOrderRelationService.queryList(map1);
			        	for(int i=0; i<goodsOrderRelationList.size(); i++) {
			        		WfGoodsOrderRelationEntity goodsOrderRelation = goodsOrderRelationList.get(i);
			        		if(1 == goodsOrderRelation.getGoodssort()) {
			    				WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
			    				productname = productname + courseInfo.getCoursename();
			    			}else if(2 == goodsOrderRelation.getGoodssort()){
			    				WfCourseChapterEntity courseChapter = courseChapterService.queryObjectIgnoreStatus(goodsOrderRelation.getGoodsid());
			    				productname = productname + courseChapter.getChaptername();
			    			}else if(3 == goodsOrderRelation.getGoodssort()){
			    				WfVipCardEntity vipCard = vipCardService.queryObject(goodsOrderRelation.getGoodsid());
			    				productname = productname + vipCard.getCardname();
			    			}
			        	}
			        	bill.setProductname(productname);//商品名称
		        	}
		            bill.setBzdatapacket("");//商户数据包
		        	double fee = Double.valueOf((String) map.get("cash_fee"))*0.006;
		        	bill.setFee(String.valueOf(Math.round(fee*100000)/100000));
		        	bill.setRate("0.6%");
		        	
		        	billService.save(bill);
	    		}

				WfMemberCouponsEntity coupon = memberCouponsService.queryObject(goodsOrder.getCouponsId());
				Map<String,Object> resultMap =new  HashMap<String,Object>();
				resultMap.put("coinvalue", goodsOrder.getSpendcoin());
				resultMap.put("oldcoppercash", goodsOrder.getOldcoppercash());
				resultMap.put("newcoppercash", goodsOrder.getNewcoppercash());
				resultMap.put("gold", goodsOrder.getGold());
				resultMap.put("newGold", goodsOrder.getNewGold());
				resultMap.put("totalCoin", goodsOrder.getSpendcoin());
				resultMap.put("price",Double.valueOf(map.get("cash_fee")));
	    		if(null != coupon) {
	    			resultMap.put("couponsCost", coupon.getCost());
	    		}else {
	    			resultMap.put("couponsCost", 0);
	    		}
	    		resultMap.put("totalPrice", goodsOrder.getOrderamount());//总金额
	    		return R.ok(resultMap);
	    	}else if("PAYERROR".equals(map.get("trade_state"))) {
	    		return R.error(57, "支付失败");
	    	}else if("ORDERPAID".equals(map.get("trade_state")) ) {
           	  	log.info("商户订单已支付");
           	  	return R.error(64, "订单已支付,请联系管理员");
	    	}else if("SIGNERROR".equals(map.get("trade_state")) ) {
           	  	log.info("签名错误");
           	  	return R.error(65, "签名错误");
	    	}else if("NOTPAY".equals(map.get("trade_state")) ) {
				log.info("订单未支付");
				return R.error(69, "订单未支付");
			}else if("ORDERNOTEXIST".equals(map.get("err_code"))){
				log.info("此交易订单号不存在");
				return R.error(69, "此交易订单号不存在");
			}
    	/*else if("USERPAYING".equals(map.get("trade_state"))) {
    		return R.error(56, "订单支付中");
    	}*/
    	}
    	return R.error("交易失败，请联系管理员。");
    }
	
    /**
     * 查询充值账单
     * @throws Exception
     */
    @RequestMapping(value = "rechargeQuery")
    @ResponseBody
    public R rechargeQuery(HttpServletRequest req) throws Exception {
    	Integer uid = ISsoLoginHelper.confirm(req);
    	String orderNum = req.getParameter("orderNum");//购物订单查询
    	String payType = req.getParameter("payType");//支付类型（1微信2支付宝，3苹果）
		String give = req.getParameter("give");//赠送铜钱
		String userSource = req.getParameter("userSource");//用户来源 +（---android/---ios/---wxh5）
		String price = req.getParameter("price");
		BigDecimal orderAmout = new BigDecimal(price);//支付费用
		
    	Map<String,String> map = new HashMap<String,String>();
    	while(!("SUCCESS".equals(map.get("trade_state")))) {
    		orderNum = req.getParameter("orderNum");//订单查询
    		
	        String appid = ConstantUtil.GG_APP_ID;
	        String partner = ConstantUtil.GG_PARTNER;
	        String partnerkey = ConstantUtil.GG_PARTNER_KEY;
	    	
	    	WXOrderQuery query = new WXOrderQuery();
	    	query.setAppid(appid);//应用APPID
	    	query.setMch_id(partner);//商户号
	    	Random random = new Random();
			String randomStr = MD5Util.MD5Encode(String.valueOf(random.nextInt(1000000)), "utf-8").toUpperCase();
			System.out.println("randomStr="+randomStr);
			query.setNonce_str(MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase());//随机字符串
	    	query.setOut_trade_no(orderNum);//商户订单号
	    	query.setPartnerKey(partnerkey);//API秘钥
	    	//query.setTransaction_id(transactionId);//微信订单号(或商户订单号 二选一)
	    	query.setSign(createSign(query, partnerkey));//签名
	    	
	    	map = query.reqOrderquery();
    	
	    	if("SUCCESS".equals(map.get("trade_state"))) {
	    		/*Map<String,Object> map2 =new  HashMap<String,Object>();
				map2.put("orderCode", orderNum);
	        	List<WfMemberGiveCoinLogEntity> memberGiveCoinLogList = memberGiveCoinLogService.queryByOrderCode(map2);
	        	for(int i=0; i<memberGiveCoinLogList.size(); i++) {
	        		WfMemberGiveCoinLogEntity memberGiveCoinLog = memberGiveCoinLogList.get(i);
		        	memberGiveCoinLog.setType(1);
		        	memberGiveCoinLog.setStatus(2);
		        	memberGiveCoinLogService.update(memberGiveCoinLog);
	        	}
	        	WfMemberGoldLogEntity memberGoldLog = memberGoldLogService.queryByOrderCode(orderNum);
	        	memberGoldLog.setType(1);
	        	memberGoldLog.setStatus(2);
	        	memberGoldLogService.update(memberGoldLog);
	        	
	        	Map<String,Object> map1 = new HashMap<String,Object>();
	        	map1.put("orderCode", orderNum);
	        	WfMemberRechargeOrderEntity memberRechargeOrder = memberRechargeOrderService.queryByOrderNum(map1);
	        	memberRechargeOrder.setOrderStatus(3);
	        	memberRechargeOrderService.update(memberRechargeOrder);*/
	    		
	    		if(!"0".equals(give)) {
	    			WfMemberGiveCoinLogEntity memberGiveCoinLog = new WfMemberGiveCoinLogEntity();//充值赠送新铜钱
	    			memberGiveCoinLog.setCoinvalue(new BigDecimal(give));//赠送铜钱
	    			memberGiveCoinLog.setCreatetime(new Date());
	    			memberGiveCoinLog.setOrdercode(orderNum);
	    			memberGiveCoinLog.setSource(8);
	    			memberGiveCoinLog.setTouserid(0);
	    			memberGiveCoinLog.setStatus(2);//1，进行中； 2，完成
	    			memberGiveCoinLog.setType(1);//1，赚；2，花
	    			memberGiveCoinLog.setUserid(uid);
	    			memberGiveCoinLog.setRemarkinfo("充值返利");
	    			memberGiveCoinLogService.save(memberGiveCoinLog);
	    		}
	    		
	    		/*WfMemberGoldLogEntity memberGoldLog = new WfMemberGoldLogEntity();
	    		memberGoldLog.setCreatetime(new Date());
	    		memberGoldLog.setGoldvalue(orderAmout);//充值的金币
	    		memberGoldLog.setOrderNo(orderNum);
	    		memberGoldLog.setStatus(2);//1，进行中； 2，完成
	    		memberGoldLog.setType(1);//1，赚；2，花
	    		memberGoldLog.setUserid(uid);
	    		memberGoldLog.setUsersource(userSource);//用户来源（android/ios/h5）
	    		memberGoldLogService.save(memberGoldLog);*/

				WfMemberNewGoldLogEntity memberNewGoldLog = new WfMemberNewGoldLogEntity();
				memberNewGoldLog.setCreatetime(new Date());
				memberNewGoldLog.setGoldvalue(orderAmout);//充值的金币
				memberNewGoldLog.setOrderNo(orderNum);
				memberNewGoldLog.setStatus(2);//1，进行中； 2，完成
				memberNewGoldLog.setType(1);//1，赚；2，花
				memberNewGoldLog.setUserid(uid);
				memberNewGoldLog.setUsersource(userSource);//用户来源（android/ios/h5）
				memberNewGoldLogService.save(memberNewGoldLog);

	    		//充值订单记录数据
	    		WfMemberRechargeOrderEntity memberRechargeOrder = new WfMemberRechargeOrderEntity();
	    		memberRechargeOrder.setUserid(uid);
	    		memberRechargeOrder.setRechargeMoney(orderAmout);
	    		memberRechargeOrder.setOrderNo(orderNum);
	    		memberRechargeOrder.setRebate(new BigDecimal(give));
	    		memberRechargeOrder.setTransactionId(map.get("transaction_id"));
	    		memberRechargeOrder.setOrderPaytime(new Date());
	    		memberRechargeOrder.setPayType(Integer.valueOf(payType));//支付类型（1微信2支付宝，3苹果）
	    		memberRechargeOrder.setOrderStatus(3);//订单类型（1生成订单2支付中3支付成功）
	    		memberRechargeOrder.setOrderTime(new Date());
	    		memberRechargeOrder.setUpdatetime(new Date());
	    		memberRechargeOrder.setUsersource("8"+userSource);//用户来源（android/ios/h5）
	    		if(!"0".equals(give)) {
	    			memberRechargeOrder.setRemark("使用微信充值"+price+"元,赠送铜钱"+give+"。");
	    		}else {
	    			memberRechargeOrder.setRemark("使用微信充值"+price+"元");
	    		}
	    		memberRechargeOrderService.save(memberRechargeOrder);
	    		return R.ok();
	    	}else if("PAYERROR".equals(map.get("trade_state"))) {
	    		return R.error(57, "支付失败");
	    	}else if("ORDERPAID".equals(map.get("trade_state")) ) {
           	  	log.info("商户订单已支付");
           	  	return R.error(64, "订单已支付,请联系管理员");
	    	}else if("SIGNERROR".equals(map.get("trade_state")) ) {
           	  	log.info("签名错误");
           	  	return R.error(65, "签名错误");
	    	}else if("NOTPAY".equals(map.get("trade_state")) ) {
				log.info("订单未支付");
				return R.error(69, "订单未支付");
			}
	    	/*else if("USERPAYING".equals(map.get("trade_state"))) {
	    		return R.error(56, "订单支付中");
	    	}*/
    	}
    	return R.error("交易失败，请联系管理员。");
    }
    
    /**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	public static String createSign(WXOrderQuery query, String AppKey) {
		SortedMap<String, String> nativeObj = new TreeMap<String, String>();
		nativeObj.put("appid", query.getAppid());
		nativeObj.put("mch_id", query.getMch_id());
		nativeObj.put("nonce_str", query.getNonce_str());
		nativeObj.put("out_trade_no", query.getOut_trade_no());
		//nativeObj.put("transaction_id", query.getTransaction_id());
		StringBuffer sb = new StringBuffer();
		Set es = nativeObj.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + AppKey);
		System.out.println("sb="+sb.toString());
		String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
		return sign;
	}

	 /**
	 * 充值卡
	 */
	@RequestMapping("/getRecharge")
	@ResponseBody
	@IgnoreToken
	public R getRecharge(HttpServletRequest req) {
		
		List<WfRechargeEntity> rechargeList = rechargeService.queryList(null);
		
		return R.ok().put("rechargeList", rechargeList);
	}

}
